/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL
v2. You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/6/6.
//
#include "sql/stmt/select_stmt.h"

#include <algorithm>
#include <unordered_map>
#include <utility>
#include <string>

#include "common/lang/string.h"
#include "common/log/log.h"
#include "sql/stmt/filter_stmt.h"
#include "storage/db/db.h"
#include "storage/table/table.h"

SelectStmt::~SelectStmt() {
  if (nullptr != filter_stmt_) {
    delete filter_stmt_;
    filter_stmt_ = nullptr;
  }
}

/**
 * @brief 将这个表table的所有属性转化成Field加入到field_metas中
 */
static void wildcard_fields(Table *table, std::vector<Field> &field_metas) {
  const TableMeta &table_meta = table->table_meta();
  const int field_num = table_meta.field_num();
  for (int i = table_meta.sys_field_num(); i < field_num; i++) {
    field_metas.push_back(Field(table, table_meta.field(i)));
  }
}

RC SelectStmt::create(Db *db, const SelectSqlNode &select_sql, Stmt *&stmt) {
  if (nullptr == db) {
    LOG_WARN("invalid argument. db is null");
    return RC::INVALID_ARGUMENT;
  }

  // collect tables in `from` statement
  std::vector<Table *> tables;
  std::unordered_map<std::string, Table *> table_map;
  for (int i = static_cast<int>(select_sql.relations.size()) - 1; i >= 0; i--) {
    const char *table_name = select_sql.relations[i].relation_name.c_str();
    if (nullptr == table_name) {
      LOG_WARN("invalid argument. relation name is null. index=%d", i);
      return RC::INVALID_ARGUMENT;
    }

    Table *table = db->find_table(table_name);
    if (nullptr == table) {
      LOG_WARN("no such table. db=%s, table_name=%s", db->name(), table_name);
      return RC::SCHEMA_TABLE_NOT_EXIST;
    }
    if (std::find(tables.begin(), tables.end(), table) == tables.end()) {
      tables.push_back(table);
    }
    table_map.insert(std::pair<std::string, Table *>(table_name, table));
    // alias新增
    if (!common::is_blank(select_sql.relations[i].relation_alias.c_str())) {
      const char *table_alias = select_sql.relations[i].relation_alias.c_str();
      table_map.insert(std::pair<std::string, Table *>(table_alias, table));
    }
  }

  // collect query fields in `select` statement
  bool have_aggregation = false;
  std::vector<AggregateUnit> tmp = select_sql.aggregations;
  // 判断是否有聚合函数，顺便判断是否合法
  for (int i = 0; i < tmp.size(); i++) {
    if (tmp[i].aggregation != NO_AGGR) {
      if (i != 0 && !have_aggregation)
        return RC::SQL_SYNTAX;
      else
        have_aggregation = true;
    }
  }
  std::vector<Field> query_fields;
  for (int i = static_cast<int>(select_sql.attributes.size()) - 1; i >= 0;
       i--) {
    const RelAttrSqlNode &relation_attr = select_sql.attributes[i];
    if (common::is_blank(relation_attr.relation_name.c_str()) &&
        0 == strcmp(relation_attr.attribute_name.c_str(), "*")) {
      for (Table *table : tables) {
        wildcard_fields(table, query_fields);
      }
    } else if (!common::is_blank(relation_attr.relation_name.c_str())) {
      const char *table_name = relation_attr.relation_name.c_str();
      const char *field_name = relation_attr.attribute_name.c_str();

      if (0 == strcmp(table_name, "*")) {
        if (0 != strcmp(field_name, "*")) {
          LOG_WARN("invalid field name while table is *. attr=%s", field_name);
          return RC::SCHEMA_FIELD_MISSING;
        }
        for (Table *table : tables) {
          wildcard_fields(table, query_fields);
        }
      } else {
        auto iter = table_map.find(table_name);
        if (iter == table_map.end()) {
          LOG_WARN("no such table in from list: %s", table_name);
          return RC::SCHEMA_FIELD_MISSING;
        }

        Table *table = iter->second;
        if (0 == strcmp(field_name, "*")) {
          wildcard_fields(table, query_fields);
        } else {
          const FieldMeta *field_meta = table->table_meta().field(field_name);
          if (nullptr == field_meta) {
            LOG_WARN("no such field. field=%s.%s.%s", db->name(), table->name(),
                     field_name);
            return RC::SCHEMA_FIELD_MISSING;
          }

          query_fields.push_back(
              Field(table, field_meta, relation_attr.attribute_alias));
        }
      }
    } else {
      if (tables.size() != 1) {
        LOG_WARN("invalid. I do not know the attr's table. attr=%s",
                 relation_attr.attribute_name.c_str());
        return RC::SCHEMA_FIELD_AMBIGUOUS;
      }

      Table *table = tables[0];
      const FieldMeta *field_meta =
          table->table_meta().field(relation_attr.attribute_name.c_str());
      if (nullptr == field_meta) {
        LOG_WARN("no such field. field=%s.%s.%s", db->name(), table->name(),
                 relation_attr.attribute_name.c_str());
        return RC::SCHEMA_FIELD_MISSING;
      }

      query_fields.push_back(
          Field(table, field_meta, relation_attr.attribute_alias));
    }
  }

  if (have_aggregation) {
    query_fields.clear();
    for (Table *table : tables) {
      wildcard_fields(table, query_fields);
    }
  }

  // check the aggregation's syntax
  for (auto it = tmp.begin(); it != tmp.end(); it++) {
    if (it->aggregation != NO_AGGR && it->aggregation != COUNT_OP &&
        it->attribute.attribute_name == "*") {
      return RC::SQL_SYNTAX;
    }
    if (tables.size() > 1 && it->attribute.relation_name == "" &&
        it->attribute.attribute_name != "*") {
      LOG_WARN("invalid. I do not know the attr's table. attr=%s",
               it->attribute.attribute_name.c_str());
      return RC::SCHEMA_FIELD_AMBIGUOUS;
    }
  }

  LOG_INFO("got %d tables in from stmt and %d fields in query stmt",
           tables.size(), query_fields.size());

  Table *default_table = nullptr;
  if (tables.size() == 1) {
    default_table = tables[0];
  }

  std::vector<OrderBySqlNode> order_tmp = select_sql.orders;
  std::vector<OrderBySqlNode> orders;
  for (auto it = order_tmp.rbegin(); it != order_tmp.rend(); it++) {
    if (tables.size() > 1 && common::is_blank(it->rel.relation_name.c_str())) {
      LOG_WARN("invalid. I do not know the attr's table. attr=%s",
               it->rel.attribute_name.c_str());
      return RC::SCHEMA_FIELD_AMBIGUOUS;
    }
    if (it->rel.relation_name == "" && default_table != nullptr) {
      it->rel.relation_name = default_table->name();
    }
    const Table *table = db->find_table(it->rel.relation_name.c_str());
    if (table == nullptr) {
      LOG_WARN("no such table. table=%s", it->rel.relation_name);
      return RC::SQL_SYNTAX;
    }
    const FieldMeta *field_meta =
        table->table_meta().field(it->rel.attribute_name.c_str());
    if (field_meta == nullptr) {
      LOG_WARN("no such field. field=%s", it->rel.attribute_name);
      return RC::SQL_SYNTAX;
    }
    orders.emplace_back(*it);
  }

  // create filter statement in `where` statement
  FilterStmt *filter_stmt = nullptr;
  RC rc = FilterStmt::create(
      db, default_table, &table_map, select_sql.conditions.data(),
      static_cast<int>(select_sql.conditions.size()), filter_stmt);
  if (rc != RC::SUCCESS) {
    LOG_WARN("cannot construct filter stmt");
    return rc;
  }

  // everything alright
  SelectStmt *select_stmt = new SelectStmt();
  select_stmt->tables_.swap(tables);
  select_stmt->query_fields_.swap(query_fields);
  select_stmt->filter_stmt_ = filter_stmt;
  select_stmt->orders_.swap(orders);
  std::vector<AggregateUnit> aggregations;

  // reverse aggregations, so that they can match the field.
  for (auto it = tmp.rbegin(); it != tmp.rend(); it++) {
    if (it->attribute.relation_name == "" && default_table != nullptr) {
      it->attribute.relation_name = default_table->name();
    }
    aggregations.emplace_back(*it);
  }
  select_stmt->aggregations_ = aggregations;
  stmt = select_stmt;
  return RC::SUCCESS;
}
